import json
from machine import Pin, PWM  
import time

class Tone:

  def __init__(self):
    self.pin = 15
    self.buzzer = PWM(Pin(self.pin))
    
    try:
      with open('/tmp/tone_conf.json') as f:
        config = json.load(f)
        self.pin = config['pin'] 
        self.buzzer = PWM(Pin(self.pin))
    except:
      pass  
      
  def play(self, freq, duration=0.5):
    # Set buzzer frequency and play for duration
    self.buzzer.freq(freq)
    time.sleep(duration)

  def off(self):
    # Turn off sound
    self.buzzer.duty_u16(0) 

  def pin(self, pin):
    # Change buzzer pin 
    self.pin = pin
    self.buzzer = PWM(Pin(self.pin))
    self.save()
     
  def execute(self, cmd):
    # Parse command string and call methods
    parts = cmd.split()

    if len(parts) == 2 and parts[0] == "tone":
      try:
        freq = int(parts[1])
        self.play(freq)  
      except ValueError:
        print("Invalid frequency")

    elif len(parts) == 3 and parts[0] == "tone":
      try:
        freq = int(parts[1])
        duration = float(parts[2])
        self.play(freq, duration)
      except ValueError:
        print("Invalid frequency or duration")

    elif len(parts) == 1 and parts[0] == "off":
      self.off()

    elif len(parts) == 2 and parts[0] == "pin":
      try:
        pin = int(parts[1])
        self.pin(pin)
      except ValueError:
        print("Invalid pin number")

    else:
      print("Unknown command")
      print("Usage:")
      print("  tone [frequency] [duration]")
      print("  tone off")
      print("  tone pin [pin number]")

  def save(self):
    # Save pin configuration to file
    config = {'pin': self.pin}
    with open('/tmp/tone_conf.json', 'w') as f:
      json.dump(config, f)

Tone().execute(args)